package socket.httpserver.redirect;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Redirector {
    private static final Logger logger = Logger.getLogger("Redirector");

    private final int port;
    private final String newSite;

    public Redirector(int port, String newSite) {
        this.port = port;
        this.newSite = newSite;
    }

    public void start() {
        try(ServerSocket server = new ServerSocket(port)) {
            logger.info("Redirecting connections on port "
                + server.getLocalPort() + " to " + newSite);

            while(true) {
                try {
                    Socket s = server.accept();
                    RedirectThread t = new RedirectThread(s, newSite);
                    t.start();

                } catch (IOException e) {
                    logger.warning("Excetion accepting connection");
                } catch (RuntimeException e) {
                    logger.log(Level.SEVERE, "Unexcepted error.", e);
                }
            }
        } catch (IOException e) {
            logger.log(Level.SEVERE, "Error opening server socket", e);
        }
    }
}
